import { ref } from 'vue'
import { defineStore } from 'pinia'
import {getAddressListAPI} from '@/API/address'
import { addAddressAPI,deleteAddressAPI,updateAddressAPI } from '@/API/address'
import { useUserStore } from '@/stores/user'
import { showToast } from 'vant'
import router from '@/router'

export const useAddressStore = defineStore('address', () => {
  

 const list =ref<any>([])
 
 //获取地址列表数据
 const setAddList =async () =>{
  const res = await getAddressListAPI()
  list.value=res.data.addresses
 
 }

//新增地址
// const userStore = useUserStore()
const addAddress=async(data:any)=>{
  
  
  const res: any = await addAddressAPI(data)
  console.log(res);
  
  if (res.code === 200) {
    showToast({
      type: 'success',
      message: res.data.message
    })
    //新增成功之后同步到store仓库
    setAddList()

    setTimeout(() => {
      router.push('/address')
    }, 2000)
  }



}

//删除地址
const deleteAddress=async(id:any) => {

 const res:any=await deleteAddressAPI(id)
  
  
 if (res.code === 200) {
  showToast({
    type: 'success',
    message: '删除成功'
  })
  //新增成功之后同步到store仓库
  setAddList()

  setTimeout(() => {
    router.push('/address')
  }, 2000)
}

}

//更新地址
const updateAddress=async(data:any)=>{
 const res:any=await updateAddressAPI(data)
 if (res?.code == 200) {
  showToast({
    type: 'success',
    message: '修改成功'
  })
  //新增成功之后同步到store仓库
  setAddList()

  setTimeout(() => {
    router.push('/address')
  }, 2000)
}
 
}

// /切换选中的地址时触发
  const isChecked =async (ev:any) =>{
    await updateAddressAPI(ev)
    setAddList()
 
  }

  return {
    setAddList,
    list,
    addAddress,
    deleteAddress,
    updateAddress,
    isChecked
   }
},
{
  persist: true,
})
